package com.damai.lifecycle.impl;

import java.util.List;

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.SchedulerException;

import com.damai.error.ErrorUtil;
import com.damai.jobcenter.QuartzPlugin;
import com.damai.lifecycle.LifeCycleListener;
import com.damai.lifecycle.LifeCycleManager;
import com.damai.utils.QuartzJob.QuartzJobListener;

public class LifeCycleManagerImpl<T> implements LifeCycleManager<T>, QuartzJobListener {
	
	LifeCycleListener<T> lifeCycleListener;
	
	public LifeCycleManagerImpl(LifeCycleListener<T> lifeCycleListener){
		
		this.lifeCycleListener = lifeCycleListener;
	}
	

	
	@Override
	public void start() {
		try {
			QuartzPlugin.me().startJob(lifeCycleListener.getCorn(), lifeCycleListener.getName(), this);
		} catch (SchedulerException e) {
			throw ErrorUtil.wrapThrow(e);
		}
	}

	@Override
	public void stop() {
		try {
			QuartzPlugin.me().stopJob(lifeCycleListener.getName());
		} catch (SchedulerException e) {
			e.printStackTrace();
		}	
	}

	
	@Override
	public void onExcecuteJob(JobExecutionContext context) throws JobExecutionException {
		List<T> list = lifeCycleListener.findException();
		for (T data : list) {
			lifeCycleListener.handleException(data);
		}
	}

	
	
}
